﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Text;
using System.Xml.Linq;


namespace MVCScaffold.Setup.CustomActions
{
    [RunInstaller(true)]
    public partial class AddinInstaller : Installer
    {
        public AddinInstaller()
        {
            InitializeComponent();
        }

        private const string nomeAddin = "MVCScaffold.AddIn";

        /// <summary>
        /// Overrides Installer.Install, which will be executed during install process.
        /// </summary>
        /// <param name="savedState">The saved state.</param>
        public override void Install(IDictionary savedState)
        {
            // Uncomment the following line, recompile the setup
            // project and run the setup executable if you want
            // to debug into this custom action.
            //Debugger.Break();
            try
            {
                base.Install(savedState);
                var nomeDiretorioInstalacao = this.Context.Parameters["targetDir"];

                XElement xml = XElement.Load(Path.Combine(nomeDiretorioInstalacao, nomeAddin), LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);

                var elementos = xml.Elements();
                var elementoAddin = elementos.Where(x => x.Name.LocalName == "Addin");
                foreach (var item in elementoAddin)
                {
                    foreach (var itemAddin in item.Elements())
                    {
                        if (itemAddin.Name.LocalName == "Assembly")
                        {
                            itemAddin.SetValue(itemAddin.Value.Replace("[namedir]", nomeDiretorioInstalacao));
                        }
                    }
                }

                if (!Directory.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"Visual Studio 2008\Addins\")))
                    Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"Visual Studio 2008\Addins\"));


                xml.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    String.Format(@"Visual Studio 2008\Addins\{0}", nomeAddin)));

                // Save AddinPath to be used in Uninstall or Rollback
                savedState.Add("targetDir", nomeDiretorioInstalacao);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }



        /// <summary>
        /// Overrides Installer.Rollback, which will be executed during rollback process.
        /// </summary>
        /// <param name="savedState">The saved state.</param>
        public override void Rollback(IDictionary savedState)
        {
            ////Debugger.Break();
            base.Rollback(savedState);

            try
            {
                string caminhoArquivo = Path.Combine(savedState["targetDir"].ToString(), "MVCScaffold.AddIn");
                if (File.Exists(caminhoArquivo))
                {
                    File.Delete(caminhoArquivo);
                }

                string caminhoAddin = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), String.Format(@"Visual Studio 2008\Addins\{0}", nomeAddin));

                if (File.Exists(caminhoAddin))
                    File.Delete(caminhoAddin);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }

        /// <summary>
        /// Overrides Installer.Uninstall, which will be executed during uninstall process.
        /// </summary>
        /// <param name="savedState">The saved state.</param>
        public override void Uninstall(IDictionary savedState)
        {
            //Debugger.Break();
            base.Uninstall(savedState);

            try
            {
                string caminhoAddin = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), String.Format(@"Visual Studio 2008\Addins\{0}", nomeAddin));
                string caminhoTemplates = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"Visual Studio 2008\Templates\aspnetscaffold");
                if (File.Exists(caminhoAddin))
                    File.Delete(caminhoAddin);

                //Exclui todos os arquivos do diretorio de templates
                DirectoryInfo directoryInfo = new DirectoryInfo(caminhoTemplates);
                foreach (var item in directoryInfo.GetFiles())
                {
                    File.Delete(item.FullName);
                }

                if (Directory.Exists(caminhoTemplates))
                    Directory.Delete(caminhoTemplates);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
    }
}
